# -*- coding: utf-8 -*-
"""
水文模型参数更新服务 - 调用外部 API 更新水文模型参数

@author: hsy
"""
import sys
from pathlib import Path
from typing import Dict, Any
import requests
from loguru import logger

# 添加项目根目录到 Python 路径
project_root = Path(__file__).resolve().parent.parent
if str(project_root) not in sys.path:
    sys.path.insert(0, str(project_root))

from config import HYDROMODEL_UPDATE_API
from utils.parameter_converter import convert_to_update_format


class HydromodelUpdateService:
    """水文模型参数更新服务"""
    
    def __init__(self):
        """初始化服务"""
        self.base_url = HYDROMODEL_UPDATE_API["base_url"]
        self.update_endpoint = HYDROMODEL_UPDATE_API["update_endpoint"]
        self.timeout = HYDROMODEL_UPDATE_API["timeout"]
        
        logger.info(f"水文模型更新服务初始化 - 目标地址: {self.base_url}{self.update_endpoint}")
    
    def update_parameters(
        self, 
        session_id: str, 
        parameter_changes: Dict[str, Any]
    ) -> Dict[str, Any]:
        """
        调用水文模型参数更新接口
        
        Args:
            session_id: 会话ID
            parameter_changes: 参数修改（扁平格式）
                例如: {"initial_state.water_level": 100.0, "parameters.B": 0.4}
        
        Returns:
            更新结果字典:
            {
                "success": bool,  # 是否成功
                "message": str,   # 结果消息
                "data": dict      # 返回的数据（如果有）
            }
        """
        try:
            # 转换参数格式（扁平 -> 嵌套）
            payload = convert_to_update_format(parameter_changes, session_id)
            
            logger.info(f"调用水文模型更新接口 - session_id: {session_id}")
            logger.debug(f"请求 payload: {payload}")
            
            # 构建完整 URL
            url = f"{self.base_url}{self.update_endpoint}"
            
            # 发送 PUT 请求
            response = requests.put(
                url,
                json=payload,
                timeout=self.timeout,
                verify=False,  # 跳过 SSL 证书验证（如果是自签名证书）
                headers={
                    "Content-Type": "application/json"
                }
            )
            
            # 抑制 SSL 警告
            import urllib3
            urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
            
            logger.info(f"更新接口响应状态码: {response.status_code}")
            
            # 处理响应
            if response.status_code == 200:
                result = response.json()
                
                # 提取关键字段
                success = result.get("success", True)
                message = result.get("message", "参数更新成功")
                data = result.get("data")
                
                if success:
                    logger.info(f"✅ 参数更新成功 - {message}")
                else:
                    logger.warning(f"⚠️ 参数更新失败 - {message}")
                
                return {
                    "success": success,
                    "message": message,
                    "data": data
                }
            else:
                # HTTP 错误
                error_message = f"更新接口返回错误: HTTP {response.status_code}"
                
                # 尝试解析错误响应
                try:
                    error_data = response.json()
                    error_message += f" - {error_data.get('message', '')}"
                except:
                    error_message += f" - {response.text[:200]}"
                
                logger.error(error_message)
                return {
                    "success": False,
                    "message": error_message,
                    "data": None
                }
        
        except requests.exceptions.Timeout:
            error_message = f"更新接口调用超时（超过 {self.timeout} 秒）"
            logger.error(error_message)
            return {
                "success": False,
                "message": error_message,
                "data": None
            }
        
        except requests.exceptions.ConnectionError as e:
            error_message = f"无法连接到更新接口: {str(e)}"
            logger.error(error_message)
            return {
                "success": False,
                "message": "无法连接到水文模型服务，请检查网络或服务状态",
                "data": None
            }
        
        except Exception as e:
            error_message = f"更新接口调用失败: {str(e)}"
            logger.error(error_message, exc_info=True)
            return {
                "success": False,
                "message": error_message,
                "data": None
            }
    
    def test_connection(self) -> bool:
        """
        测试与更新接口的连接
        
        Returns:
            bool: 连接是否正常
        """
        try:
            # 尝试访问健康检查接口（如果有）
            url = f"{self.base_url}/health"
            response = requests.get(url, timeout=5, verify=False)
            
            if response.status_code == 200:
                logger.info(f"✅ 更新接口连接测试成功")
                return True
            else:
                logger.warning(f"⚠️ 更新接口连接测试失败: HTTP {response.status_code}")
                return False
        
        except Exception as e:
            logger.error(f"❌ 更新接口连接测试失败: {str(e)}")
            return False


# 使用示例
if __name__ == "__main__":
    logger.info("测试水文模型更新服务...")
    
    try:
        # 初始化服务
        service = HydromodelUpdateService()
        
        # 测试连接
        service.test_connection()
        
        # 测试更新参数
        test_changes = {
            "initial_state.water_level": 100.10,
            "parameters.B": 0.4
        }
        
        result = service.update_parameters(
            session_id="test_session_123",
            parameter_changes=test_changes
        )
        
        logger.info(f"测试结果: {result}")
        
    except Exception as e:
        logger.error(f"测试失败: {e}", exc_info=True)


